package com.liujie.controller;

import com.liujie.common.R;
import com.liujie.pojo.Photo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Value("${file.path}")
    private String basePath;

    private static int number=0;

    private static String url;

    /**
     * 文件上传
     * @param file 待上传的文件
     */
    @PostMapping("/upload")
    public void upload(MultipartFile file){
        File dir=new File(basePath);
        if (!dir.exists()){
            dir.mkdir();
        }
        String originalFilename = file.getOriginalFilename();
        String houzhui = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            file.transferTo(new File(basePath+number+houzhui));
            log.info("上传文件:"+number+houzhui);
            number++;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/updateUrl")
    public void updateUrl(@RequestBody Map<String,String> map){
        FileController.url = map.get("url");
        log.info("新路径："+url);
    }

    /**
     * 获取文件夹下所有图片
     * @param map 文件路径
     * @return 数据
     */
    @PostMapping("/search")
    public R<List<Photo>> search(@RequestBody Map<String,String> map){
        String path = map.get("path");
        List<Photo> res=new ArrayList<>();
        File file=new File(path);//文件夹
        if (file.isDirectory()){
            String[] files = file.list();
            for (String f : files) {
                if (f.contains("png") || f.contains("jpg")){
                    Photo photo=new Photo();
                    photo.setName(f);
                    photo.setUrl(path+f);
                    res.add(photo);
                }
            }
        }else{
            return R.error("目录不存在");
        }
        return R.success(res);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            //通过字节输入流拿到文件
            FileInputStream fileInputStream=new FileInputStream(new File(url+name));
            //通过字节输出流将文件写到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置写回文件类型
            response.setContentType("image/jpeg");
            //向浏览器写数据
            int len=0;
            byte[] b=new byte[1024];
            while ((len=fileInputStream.read(b))!=-1){
                outputStream.write(b,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
